package com.rock.securityresearch.util

import com.rock.securityresearch.common.TimePeriod
import com.rock.securityresearch.equity.HistoricalStockQuote
import com.rock.securityresearch.common.toDate

import java.time.{DayOfWeek, LocalDate}
import scala.collection.mutable.ArrayBuffer

object HistoricalStockQuoteUtil {

    def groupBy(datas: List[HistoricalStockQuote], period: TimePeriod): List[List[HistoricalStockQuote]] = {
        val map = datas.map(quote => (quote.date.toDate(), quote)).toMap
        val dates = datas.map(data => data.date.toDate())
        period match
            case TimePeriod.Daily => List(datas)
            case TimePeriod.Weekly => DateUtil.groupByWeek(dates).map(dateList => dateList.map(date => map(date)))
            case TimePeriod.Monthly => DateUtil.groupByMonth(dates).map(dateList => dateList.map(date => map(date)))
            case TimePeriod.Yearly => DateUtil.groupByYear(dates).map(dateList => dateList.map(date => map(date)))
    }


    def getStockQuote(datas: List[HistoricalStockQuote], period: TimePeriod): List[HistoricalStockQuote] ={
        val groupedDatas = groupBy(datas, period)
        val res = period match
            case TimePeriod.Daily => groupedDatas.head
            case _ => groupedDatas.map(ds => ds.head)
        res.sortWith((d1, d2) => d2.date.compareTo(d1.date) > 0)
    }

}
